const fs = require('fs')
const path = require('path')
const ora = require('ora')
const uuid = require('uuid/v1')
const rimraf = require('rimraf')
const superagent = require('superagent')
const iconfount = require('iconfount')
const { resolve,prefix } = require('./utils')

const fetchSpinner = ora('获取图标文件中...')

const tempDir = path.join(__dirname, '..', uuid())


module.exports = async (themeId) => {
  console.info('模板Id',themeId)
  if (!themeId){
    console.error('模板Id不能为空')
    return
  } 
  const res = await superagent
    .get('/iconitem/GetIconItemListByThemeId', {
      themeId: themeId
  }).use(prefix)
  const { result, status } = res.body
  if (status !== 1){
    console.info('图标获取接口请求错误',res.message)
    return
  } 
  console.info('图标获取成功,图标总数量',result.length)
  fs.mkdirSync(tempDir)
  fetchSpinner.start()

  const queue = result.map(svg => {
    return new Promise(async (reslove, reject) => {
      const svgRes = await superagent
        .get(`http://diyapi.5ug.com${svg.path}`)

      const filename = path.join(tempDir, svg.name)
      fs.writeFile(filename, svgRes.body, (err) => {
        if (err) reject(err)
        reslove(svg.name)
      })
    })
  })

  await Promise.all(queue)

  fetchSpinner.stop()

  const glyphs = result.map((svg) => {
    const pureName = svg.name.replace(/\.svg$/, '').replace('zkicon-', '')
    return {
      src: svg.name,
      css: pureName
    }
  })
  var outputPath='src/assets/style/iconfont'
  if(themeId==='all'){
    outputPath='src/assets/style/iconall'
  }

  const config = {
    name: 'iconfount',
    output: resolve(outputPath),
    hinting: false,
    units_per_em: 1000,
    ascent: 850,
    weight: 400,
    start_codepoint: 59392,
    glyphs_dir: '.',
    glyphs,
    meta: {
      author: '5ug',
      license: 'MIT',
      license_url: 'https://opensource.org/licenses/MIT',
      homepage: 'http://www.5ug.com',
      css_prefix_text: '',
      css_use_suffix: false,
      columns: 4,
      filename_hash: true
    }
  }
  const configPath = path.join(tempDir, 'config.json')
  fs.writeFileSync(configPath, JSON.stringify(config, null, '  '))

  await iconfount(configPath)

  rimraf(tempDir, (err) => {
    if (err) console.log(err)
  })
  console.info('图标生成成功')
}
